
from flask_restful import Resource
from flask import request
from common.resp import ajax_success, ajax_error, ajax_data, ajax_page
from core import db
from datetime import datetime

# 摄像机
class CameraModel(db.Model):
    __tablename__ = "sys_camera"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    name = db.Column(db.String(100), nullable=False, index=True) # 摄像机名称
    ip = db.Column(db.String(100), nullable=False) # 摄像机IP地址
    type = db.Column(db.String(1), nullable=False) # 采集方式 1-rtsp 2-http
    url = db.Column(db.String(255), nullable=True) # 采集地址
    status = db.Column(db.String(10), default="1")  #状态 禁用 启用 故障
    create_time = db.Column(db.DateTime, nullable=True, default=datetime.now)
    update_time = db.Column(db.DateTime, nullable=True, default=datetime.now, onupdate=datetime.now)

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "ip": self.ip,
            "type": self.type,
            "url": self.url,
            "status": self.status,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S") if self.create_time else None,
            "update_time": self.update_time.strftime("%Y-%m-%d %H:%M:%S") if self.update_time else None,
        }

class CameraResource(Resource):
    def get(self):
        query = request.args;
        filters = []
        if query.get('name'):
            filters.append(CameraModel.name.like('%' + query['name'] + '%'))
        if query.get('type'):
            filters.append(CameraModel.type == query['type'])
        if query.get('status'):
            filters.append(CameraModel.status == query['status'])

        paginate = CameraModel.query.filter(
            *filters).paginate(
            page=int(query.get('page', 1)), per_page=int(query.get('limit', 10)), error_out=False)

        return ajax_page([item.to_json() for item in paginate.items], paginate.total)

    def post(self):
        data = request.get_json()
        model = CameraModel(
            name = data.get('name'),
            ip = data.get('ip'),
            type = data.get('type', 'rtsp'),
            url = data.get('url'),
            status = data.get('status', '1')
        )

        db.session.add(model)
        db.session.commit()
        return ajax_success('摄像机创建成功')

    def put(self):
        data = request.get_json()
        if not data.get('id'):
            return ajax_error('参数错误')

        model = CameraModel.query.get_or_404(data.get('id'))
        if not model:
            return ajax_error('摄像机不存在')

        if data.get('name'):
            model.name = data.get('name', model.name)
        if data.get('status'):
            model.status = data.get('status', model.status)
        if data.get('ip'):
            model.ip = data.get('ip', model.ip)
        if data.get('type'):
            model.type = data.get('type', model.type)
        if data.get('url'):
            model.url = data.get('url', model.url)
        if data.get('status'):
            model.status = data.get('status', model.status)

        db.session.add(model)
        db.session.commit()
        return ajax_success('摄像机更新成功')

class CameraDetail(Resource):
    def get(self, id):
        if id:
            model = CameraModel.query.get_or_404(id)
            return ajax_data(model.to_json())
        else:
            return ajax_error('参数错误')

    def delete(self, id):
        from modules.collection import CollectionModel
        t = CollectionModel.query.filter_by(camera_id=id).first()
        if t:
            return ajax_error('删除摄像机前请先删除采集任务')

        #再删除数据库
        camera = CameraModel.query.get_or_404(id);
        db.session.delete(camera)
        db.session.commit()
        return ajax_success('摄像机删除成功')

